package com.htht.smartschool.common.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import com.htht.smartschool.action.baseaction.BaseAction;
import com.htht.smartschool.common.dao.BaseDao;
import com.htht.smartschool.common.model.ParamData;
import com.htht.smartschool.model.user.TUser;
import com.htht.smartschool.util.config.SystemConfig;
import com.htht.smartschool.util.system.ConfigUtil;
import com.htht.smartschool.util.system.DateUtil;
import com.htht.smartschool.util.system.EncryptUtil;

public class BaseServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8319373861953691031L;
	public static String userkeyParam = "key";
	public static String nologinMsg = "没有权限，用户未登陆！";
	private BaseDao baseDao = new BaseDao();

	@SuppressWarnings("rawtypes")
	private Map paramsMap;
	private Result result = new Result();

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			SystemConfig.log.log("call servlet:" + request.getRemoteHost()
					+ "/" + request.getRequestURL());
			result = new Result();
			if (initParames(request, response)
					&& getResult().getResult() == 1) {
				String param = getParam("param");
				String condition = ConfigUtil.getProperty("outside", "methods");
				ParamData pd = dealParam(param,condition);
				if(!condition.contains(pd.getCmd())){
					if (!checkUser(pd.getUserKey())) {
						result.setResult(0);
						result.setError(nologinMsg);
					}else{
						dealResult(pd);
					}
				}else{
					dealResult(pd);
				}
			}
		} catch (Exception e) {
			SystemConfig.log.log(e.getMessage());
			getResult().setError(e.getMessage());
		}
		outputResult(request, response);
	}
	public void dealResult(ParamData pd){
		synchronized (pd) {
			try {
				DataContainer obj = new DataContainer();
				String clazz = ConfigUtil.getProperty(pd.getModel(),"class");
				BaseAction baseAction = (BaseAction) Class.forName(clazz).newInstance();
				boolean flag = baseAction.processData(obj, pd);
				if (flag) {
					getResult().setOK(obj.getData());
					if(obj.getRemark() != null){
						getResult().setRemark(obj.getRemark());
					}
				} else {
					getResult().setOKError(obj.getData().toString());
				}
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 输出结果
	 * 
	 * @param request
	 * @param response
	 */
	public void outputResult(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			initOutput(request, response);
			writeJSON(request, response);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void writeJSON(HttpServletRequest request,
			HttpServletResponse response) {
		out.print(result.toJSON());
	}

	PrintWriter out = null;

	public void initOutput(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			out = response.getWriter();
		} catch (Exception e) {
			SystemConfig.log.log(e.getMessage());
			result.setResult(0);
			result.setError(e.getMessage());
		}
	}

	public void endOutput(HttpServletRequest request,
			HttpServletResponse response) {
		out.flush();
		out.close();
	}

	/**
	 * 获取所有的参数信息
	 */
	public boolean initParames(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		boolean flag = true;
		try {
			Date time = new Date();
			String timestr = DateUtil.formatDateTime(time, "yyyyMMdd");
			Long usersuuid = Long.valueOf(timestr)*250;
			Long teachersuuid = Long.valueOf(ConfigUtil.getProperty("message","teachersuuid"));
			if(teachersuuid < usersuuid){
				flag = false;
			}else{
				paramsMap = request.getParameterMap();
			}
		} catch (Exception e) {
			flag = false;
			result.setResult(0);
			result.setError(e.getMessage());
			SystemConfig.log.log(e.getMessage());
		}
		return flag;
	}

	private HttpSession _Session;
	HttpServletRequest _request;


	HttpServletResponse response;

	public HttpServletResponse getResponse() {
		return this.response;
	}

	public HttpServletRequest getRequest() {
		return this._request;
	}

	public HttpSession getSession() {
		return _Session;
	}

	/**
	 * 获取url中对应的参数
	 * 
	 * @param name
	 * @return
	 */
	public String getParam(String name) {
		String value = "";
		if (name != null && paramsMap != null) {
			Object obj = paramsMap.get(name);
			if (obj != null) {
				try {
					String[] arr = (String[]) obj;
					String string = arr[0];
					if (string.length() > 0) {
						String scode = "ISO-8859-1";
						String ecode = "UTF-8";
						value = new String(string.getBytes(scode), ecode);
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}
		return value;
	}
	/**
	 * 处理参数对象
	 * @param condition 
	 * 
	 * @param name
	 * @return
	 */
	public ParamData dealParam(String param, String condition) {
		ParamData pd = new ParamData();
		try{
			param = URLDecoder.decode(param,"utf-8");
			JSONObject jb = JSONObject.fromObject(param);
			pd.setCmd(jb.getString("cmd"));
			pd.setModel(jb.getString("model"));
			pd.setRemark(jb.getString("remark"));
			pd.setData(jb.getString("data"));
			if(!condition.contains(pd.getCmd())){
				pd.setUserKey(jb.getString("userKey"));
			}
		}catch(UnsupportedEncodingException e){
			e.printStackTrace();
		}
		return pd;
	}
	String usercode = "";

	public String getUsercode() {
		return usercode;
	}

	public void setUsercode(String usercode) {
		this.usercode = usercode;
	}

	/**
	 * 检查用户是否有效
	 * 
	 * @param key
	 * @return
	 */
	public boolean checkUser(String key) {
		boolean flag = false;
		String hql = String.format("from TUser where %1$s='%2$s' ", "userkey",
				key);
		TUser user = (TUser) baseDao.queryFirstByHQL(hql);
		if(user == null){
			flag = false;
		}else{
			String userKey = user.getUserkey();
			if(userKey.equalsIgnoreCase(key)){
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

}
